package scheduletask;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CancelAvaliable {


    // 需要停止任意一个定时任务的方案
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        HashMap<String, Future<?>> futures = new HashMap<>();

        var executor = new ScheduledThreadPoolExecutor(1,
            new ThreadFactoryBuilder().setNameFormat("-executor-%d").setDaemon(false).build());

        ScheduledFuture<?> future1 =
            executor.scheduleAtFixedRate(() -> System.out.println("cancel 1"), 0, 2, TimeUnit.SECONDS);
        futures.put("future1", future1);

        ScheduledFuture<?> future2 =
            executor.scheduleAtFixedRate(() -> System.out.println("cancel 2"), 1, 1, TimeUnit.SECONDS);

        // toString方法保存了过多内容，只标识的话并不需要
//        futures.put(future2.toString(), future2);
        futures.put("future2", future2);

        System.out.println(futures);

    }
}
